package cn.jksoft.businessclient.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;

import com.facebook.drawee.backends.pipeline.Fresco;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingApi;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseSwipeBackCompatActivity;
import cn.jksoft.businessclient.bean.OrderDetailEntity;
import cn.jksoft.businessclient.bean.OrderDetailStatusEntity;
import cn.jksoft.businessclient.ui.adapter.OrderDetailAdapter;
import cn.jksoft.businessclient.utils.DialogHelp;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class OrderDetailActivity extends BaseSwipeBackCompatActivity {

    @Bind(R.id.order_detail_expandable_list)
    ExpandableListView expandableListView;
    private OrderDetailAdapter mAdapter;
    private ProgressDialog waitDialog;
    private List<String> groupData = new ArrayList<String>();
    private List<Object> childData = new ArrayList<Object>();
    private String isFastBillingOrder = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fresco.initialize(this);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        initTitle(getIntent().getStringExtra("carPlateNum")!=null?getIntent().getStringExtra("carPlateNum"):"订单详情");
        initBackClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initView();
        if(BaseApplication.getInstance().getLoginEntity() == null ||
                BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO() == null){
            finish();
            readyGo(LoginActivity.class);
        }else{
            loadOrderProductData();
        }
    }

    private void initView() {
        groupData.add("订单详情");
        groupData.add("最新动态");
        mAdapter = new OrderDetailAdapter(this, groupData, childData);
        expandableListView.setAdapter(mAdapter);

    }

    private void loadOrderProductData() {
        waitDialog  = DialogHelp.getWaitDialog(this,"正在加载...");
        waitDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("outboundId", getIntent().getStringExtra("outboundId"));
            json.put("messId",getIntent().getStringExtra("messageId"));
            json.put("operId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.getOrderDetailProductList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderDetailEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onNext(OrderDetailEntity entity) {

                        String retCode = entity.getIs_successful();
                        if ("1".equals(retCode)) {
                            isFastBillingOrder = entity.getOrderDetails().getIS_FAST_BILLING_ORDER();
                            mAdapter.addChildData(entity.getOrderDetails(),isFastBillingOrder);
                            loadOrderStatusData();
                        }
                    }
                });
    }

    private void loadOrderStatusData() {

        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("outboundId", getIntent().getStringExtra("outboundId"));
            json.put("messId",getIntent().getStringExtra("messageId"));
            json.put("operId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.getOrderDetailStatusList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderDetailStatusEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onNext(OrderDetailStatusEntity entity) {

                        String retCode = entity.getIs_successful();
                        if ("1".equals(retCode)) {
                            mAdapter.addChildData(entity.getCustomerReceiptsMessList(),isFastBillingOrder);
                        }
                        int groupCount= expandableListView.getCount();
                        for (int i=0; i<groupCount; i++) {
                            expandableListView.expandGroup(i);
                        };
                        waitDialog.dismiss();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            mAdapter.setChildData(new ArrayList<Object>());
            mAdapter.notifyDataSetChanged();
            loadOrderProductData();

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        if(getIntent().getBooleanExtra("isShowAdd",false)) {
            getMenuInflater().inflate(R.menu.order_detail_menu, menu);
        }
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_add) {
            Intent intent = new Intent(OrderDetailActivity.this,CreateOrderActivity.class);
            intent.putExtra("isAddOrder",true);
            intent.putExtra("outboundId",Long.parseLong(getIntent().getStringExtra("outboundId")));
            if(childData.size()>0){
                OrderDetailEntity.OrderDetailsBean bean = (OrderDetailEntity.OrderDetailsBean) childData.get(0);
                if(bean!=null){
                    intent.putExtra("CUSTOMER_ID",bean.getCUSTOMER_ID());
                    intent.putExtra("CUST_CM_ID",bean.getCUST_CM_ID());
                    intent.putExtra("CAR_PLATE_NUM",bean.getCAR_PLATE_NUM());
                    intent.putExtra("CUSTOMER_NAME",bean.getCUSTOMER_NAME());
                }
            }
            startActivityForResult(intent,0,null);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
